<?php
use think\Controller;
use think\Session;
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/**
 * 是否Post请求
 * @return mixed
 */
function IsPost(){
    $IsPost = \think\Request::instance()->isPost();
    return $IsPost;
}

/**
 * 请求数据
 * @param string $str
 * @return mixed
 */
function Param($str=''){
    if($str == ''){
        $Param = \think\Request::instance()->Param();
    }else{
        $Param = \think\Request::instance()->Param($str);
    }

    return $Param;
}

/**
 * 会员列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function UserList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'level' => 0,
            'name' => '',
            'phone' => '',
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
            'id' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user')->order('status desc')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user')->where($Where)->order('status desc')->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $UserList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $UserList as $k=>$v){
        //等级信息
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserList[$k]['level']])->find();
        if(empty($LevelInfo)){
            $UserList[$k]['level'] = "普通用户";
        }else{
            $UserList[$k]['level'] = $LevelInfo['name'];
        }

        //推荐人信息
        $RecommendInfo = UserInfo(['id'=>$UserList[$k]['recommend']]);
        $UserList[$k]['recommend'] = $RecommendInfo['username'];
    }

    return ['UserList'=>$UserList,'Page'=>$Page];
}

/**
 * 会员表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function UserCount($Where=[]){
    if(empty($Where)){
        $UserCount = \think\Db::name('user')->count();
    }else{
        $UserCount = \think\Db::name('user')->where($Where)->count();
    }

    return $UserCount;
}

/**
 * 会员信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function UserInfo($Where){
    $UserInfo = \think\Db::name('user')->where($Where)->find();

    return $UserInfo;
}

/**
 * 等级列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelList($Where=[]){
    if(empty($Where)){
        $LevelList = \think\Db::name('user_level')->order('id asc')->select();
    }else{
        $LevelList = \think\Db::name('user_level')->where($Where)->where('id asc')->select();
    }

    return $LevelList;
}

/**
 * 等级详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelInfo($Where){
    $LevelInfo = \think\Db::name('user_level')->where($Where)->find();

    return $LevelInfo;
}

/**
 * 等级申请列表
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function LevelApplyList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'username' => '',
            'status' => 5,
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_level_apply')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_level_apply')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $LevelApplyList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $LevelApplyList as $k=>$v){
        //会员信息
        $UserInfo = \think\Db::name('user')->where(['id'=>$LevelApplyList[$k]['user_id']])->find();
        $LevelApplyList[$k]['username'] = $UserInfo['username'];

        //定存金额
        $LevelApplyList[$k]['balance'] = \think\Db::name('user_deposit')->where(['user_id'=>$LevelApplyList[$k]['user_id']])->sum('surplus_num');

        //当前等级
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserInfo['level']])->find();
        if(empty($LevelInfo)){
            $LevelApplyList[$k]['now_level'] = "暂未开卡";
        }else{
            $LevelApplyList[$k]['now_level'] = $LevelInfo['name'];
        }

        //等级信息
        $LevelInfo = \think\Db::name('user_level')->where(['id'=>$LevelApplyList[$k]['level_id']])->find();
        $LevelApplyList[$k]['level_name'] = $LevelInfo['name'];

    }

    return ['LevelApplyList'=>$LevelApplyList,'Page'=>$Page];
}

/**
 * 等级申请记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function LevelApplyCount($Where=[]){
    if(empty($Where)){
        $LevelApplyCount = \think\Db::name('user_level_apply')->count();
    }else{
        $LevelApplyCount = \think\Db::name('user_level_apply')->where($Where)->count();
    }

    return $LevelApplyCount;
}

/**
 * 奖金列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FinanceList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'reward_type' => 0,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
            'from' => '',
            'order_id' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('finance')->order('id desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('finance')->where($Where)->order('id desc')->paginate('13',false,['query'=>$query]);

    }

    $FinanceList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($FinanceList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$FinanceList[$k]['user_id']]);
        // $FromInfo = UserInfo(['id'=>$FinanceList[$k]['from_id']]);
        if($v['reward_type'] == 1 || $v['reward_type'] == 2){
            $FromInfo = Db::name('admin')->where(['id'=>$FinanceList[$k]['from_id']])->find();
            $FromInfo['level'] = 1;
        }else{
            $FromInfo = UserInfo(['id'=>$FinanceList[$k]['from_id']]);
            $FromInfo['level'] = $FromInfo['level'];
        }

        $FinanceList[$k]['user_name'] = $UserInfo['username'];
        $FinanceList[$k]['from_name'] = $FromInfo['username'];
        $LevelInfo = LevelInfo(['id'=>$FromInfo['level']]);
        $FinanceList[$k]['from_level'] = $LevelInfo['name'];
    }
//dump($FinanceList);die;
    return ['FinanceList'=>$FinanceList,'Page'=>$Page];
}

/**
 * 奖金表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function FinanceCount($Where=[]){
    if(empty($Where)){
        $FinanceCount = \think\Db::name('finance')->count();
    }else{
        $FinanceCount = \think\Db::name('finance')->where($Where)->count();
    }
//dump($FinanceCount);die;
    return $FinanceCount;
}

/**
 * 定存列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function DepositList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'cycle' => 0,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_deposit')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_deposit')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $DepositList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($DepositList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$DepositList[$k]['user_id']]);
        $DepositList[$k]['user_name'] = $UserInfo['username'];

        $LevelInfo = LevelInfo(['id'=>$UserInfo['level']]);
        $DepositList[$k]['level_name'] = $LevelInfo['name'];
    }

    return ['DepositList'=>$DepositList,'Page'=>$Page];
}

/**
 * 定存记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function DepositCount($Where=[]){
    if(empty($Where)){
        $FinanceCount = \think\Db::name('user_deposit')->count();
    }else{
        $FinanceCount = \think\Db::name('user_deposit')->where($Where)->count();
    }

    return $FinanceCount;
}

/**
 * 公告列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function NoticeList(){
    $List = \think\Db::name('notice')->order('sort asc')->paginate(20);
    $NoticeList = $List->toArray()['data'];
    $Page = $List->render();
    return ['NoticeList'=>$NoticeList,'Page'=>$Page];
}

/**
 * 公告记录条数
 * @return int|string
 * @throws \think\Exception
 */
function NoticeCount(){
    $NoticeCount = \think\Db::name('notice')->count();
    return $NoticeCount;
}

/**
 * 公告详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function NoticeInfo($Where){
    $NoticeInfo = \think\Db::name('notice')->where($Where)->find();
    return $NoticeInfo;
}

/**
 * 应用列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function AppList(){
    $List = \think\Db::name('app')->order('id desc')->paginate(20);
    $AppList = $List->toArray()['data'];
    $Page = $List->render();
    return ['AppList'=>$AppList,'Page'=>$Page];
}

/**
 * 应用记录条数
 * @return int|string
 * @throws \think\Exception
 */
function AppCount(){
    $AppCount = \think\Db::name('app')->count();
    return $AppCount;
}

/**
 * 应用详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function AppInfo($Where){
    $AppInfo = \think\Db::name('app')->where($Where)->find();
    return $AppInfo;
}

/**
 * 反馈列表
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FeedbackList(){
    $List = \think\Db::name('feedback')->order('id desc')->paginate(20);
    $FeedbackList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($FeedbackList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$FeedbackList[$k]['user_id']]);
        $FeedbackList[$k]['username'] = $UserInfo['username'];
    }

    return ['FeedbackList'=>$FeedbackList,'Page'=>$Page];
}

/**
 * 反馈记录条数
 * @return int|string
 * @throws \think\Exception
 */
function FeedbackCount(){
    $FeedbackCount = \think\Db::name('feedback')->count();
    return $FeedbackCount;
}

/**
 * 反馈详细信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function FeedbackInfo($Where){
    $FeedbackInfo = \think\Db::name('feedback')->where($Where)->find();
    return $FeedbackInfo;
}

/**
 * 添加流水明细
 * @param $user_id
 * @param $from_id
 * @param $num
 * @param $type
 * @param $reward_type
 * @param $remarks
 */
function FinanceAdd($user_id,$from_id,$num,$type,$reward_type,$remarks,$order_id='',$deposit_id=''){

    $DataAdd = [
        'user_id' => $user_id,
        'from_id' => $from_id,
        'num' => $num,
        'type' => $type,
        'reward_type' => $reward_type,
        'remarks' => $remarks,
        'order_id' => $order_id,
        'add_time' => time(),
        'deposit_id' => $deposit_id,

    ];

    $Res = \think\Db::name('finance')->insert($DataAdd);
    return $Res;
}

/**
 * 银行信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function BankInfo($Where){

    $BankInfo = \think\Db::name('user_bank')->where($Where)->find();
    return $BankInfo;
}

/**
 * 提现记录
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function WithdrawList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'status' => 5,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_withdraw')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_withdraw')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $WithdrawList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($WithdrawList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$WithdrawList[$k]['user_id']]);
        $WithdrawList[$k]['user_name'] = $UserInfo['username'];
    }

    return ['WithdrawList'=>$WithdrawList,'Page'=>$Page];
}

/**
 * 提现记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function WithdrawCount($Where=[]){
    if(empty($Where)){
        $WithdrawCount = \think\Db::name('user_withdraw')->count();
    }else{
        $WithdrawCount = \think\Db::name('user_withdraw')->where($Where)->count();
    }

    return $WithdrawCount;
}

/**
 * 充值记录
 * @param array $Where
 * @return array
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function RechargeList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'status'=>5,
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_recharge')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_recharge')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }

    $RechargeList = $List->toArray()['data'];
    $Page = $List->render();

    foreach($RechargeList as $k=>$v){
        $UserInfo = UserInfo(['id'=>$RechargeList[$k]['user_id']]);
        $RechargeList[$k]['user_name'] = $UserInfo['username'];
    }

    return ['RechargeList'=>$RechargeList,'Page'=>$Page];
}

/**
 * 充值记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function RechargeCount($Where=[]){
    if(empty($Where)){
        $RechargeCount = \think\Db::name('user_recharge')->count();
    }else{
        $RechargeCount = \think\Db::name('user_recharge')->where($Where)->count();
    }

    return $RechargeCount;
}

/**
 * 商品列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function GoodsList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'son_id' => 0,
            'name' => '',
            'is_shelf' => 0,
            'goods_type' =>0,
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('goods')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('goods')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $GoodsList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $GoodsList as $k=>$v){

        //父级分类信息
        $ParentClassInfo = \think\Db::name('goods_class')->where(['id'=>$GoodsList[$k]['parent_id']])->find();
        $GoodsList[$k]['parent_class'] = $ParentClassInfo['name'];

        //子级分类信息
        $SonClassInfo = \think\Db::name('goods_class')->where(['id'=>$GoodsList[$k]['son_id']])->find();
        $GoodsList[$k]['son_class'] = $SonClassInfo['name'];

    }

    return ['GoodsList'=>$GoodsList,'Page'=>$Page];
}

/**
 * 商品表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function GoodsCount($Where=[]){
    if(empty($Where)){
        $UserCount = \think\Db::name('goods')->count();
    }else{
        $UserCount = \think\Db::name('goods')->where($Where)->count();
    }

    return $UserCount;
}

/**
 * 商品信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function GoodsInfo($Where){
    $GoodsInfo = \think\Db::name('goods')->where($Where)->find();
    return $GoodsInfo;
}

/**
 * 订单列表
 * @param array $Where
 * @return false|PDOStatement|string|\think\Collection
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function OrderList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
            'order_id' => '',
            'status' => 9,
            'name' => '',
            'phone' => '',
            'username' => '',
            'begin_time' => '',
            'end_time' => '',
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_order')->order('add_time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_order')->where($Where)->order('add_time desc')->paginate('13',false,['query'=>$query]);

    }

    $OrderList = $List->toArray()['data'];
    $Page = $List->render();

    foreach( $OrderList as $k=>$v){
        //会员信息
        $UserInfo = \think\Db::name('user')->where(['id'=>$OrderList[$k]['user_id']])->find();
        $OrderList[$k]['username'] = $UserInfo['username'];
        //产品信息
        //所有商品id
        $goods_id = explode(',', $OrderList[$k]['goods_id']);
        foreach ($goods_id as $key=>$val) {
            $GoodsInfo = \think\Db::name('goods')->where(['id'=>$val])->find();
            $goods['logo_url'] = $GoodsInfo['logo_url'];
            $goods['goods_name'] = $GoodsInfo['name'];
            $goods['price'] = $GoodsInfo['price'];
            $goods['num'] = $goods_id[$key];
            $OrderList[$k]['goods'][] = $goods;
        }
        
    }
//     echo "<pre>";
// var_dump($OrderList);die;
    return ['OrderList'=>$OrderList,'Page'=>$Page];
}

/**
 * 订单表记录条数
 * @param array $Where
 * @return int|string
 * @throws \think\Exception
 */
function OrderCount($Where=[]){
    if(empty($Where)){
        $OrderCount = \think\Db::name('user_order')->count();
    }else{
        $OrderCount = \think\Db::name('user_order')->where($Where)->count();
    }

    return $OrderCount;
}

/**
 * 订单信息
 * @param $Where
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function OrderInfo($Where){
    $OrderInfo = \think\Db::name('user_order')->where($Where)->find();

    return $OrderInfo;
}

/**
 * 系统参数
 * @return array|false|PDOStatement|string|\think\Model
 * @throws \think\db\exception\DataNotFoundException
 * @throws \think\db\exception\ModelNotFoundException
 * @throws \think\exception\DbException
 */
function Config(){

    $Config = \think\Db::name('system_config')->where(['id'=>1])->find();

    return $Config;
}

/**
 * 保存验证码信息
 * @param $phone
 * @param $code
 */
function AddCode($phone,$code){
    $Data = [
        'phone' => $phone,
        'code' => $code,
        'send_time' => time(),
    ];
    \think\Db::name('user_code')->insert($Data);
}

/**
 * 判断验证码是否正确
 * @param $phone
 * @param $code
 * @return array
 */
function checkCode($phone,$code)
{
    //根据手机号找出最后一条验证码
    $CodeInfo = \think\Db::name('user_code')->where(['phone' => $phone])->order('send_time desc')->find();
    //判断验证码是否存在
    if(empty($CodeInfo)){
        return ['status'=>0,'message'=>'验证码不存在'];
    }
    //输入的验证码是否一致
    if($CodeInfo['code'] != $code){
        return ['status'=>0,'message'=>'验证码错误'];
    }
    //判断验证码已发送多长时间
    $Duration = (time() - $CodeInfo['send_time']) / 60 ;
    if($Duration > 10){  //有效期10分钟
        return ['status'=>0,'message'=>'验证码已过期'];
    }
    //判断验证码状态
    if($CodeInfo['status'] == 1){
        return ['status'=>0,'message'=>'验证码已失效'];
    }

    //验证通过
    //通过后改变验证码使用状态
    \think\Db::name('user_code')->where(['id'=>$CodeInfo['id']])->update(['status'=>1]);
    //返回信息
    return ['status'=>1];
}

function consume_log($content){
    header("Content-type: text/html; charset=utf-8");
    $time = date('Ymd',time());
//    $file  = APP_PATH.'../log.txt';//要写入文件的文件名（可以是任意文件名），如果文件不存在，将会创建一个
    $file  = APP_PATH.'../log/log'.$time.'.txt';//要写入文件的文件名（可以是任意文件名），如果文件不存在，将会创建一个
//    $content = "第一次写入的内容\n";

    if($f  = file_put_contents($file, $time."\n".$content."\n",FILE_APPEND)){// 这个函数支持版本(PHP 5)
//        echo "写入成功。<br />";
    }
}

/**
 * 获取随机数
 * @param int $len
 * @return bool|string
 */
function randNumber($len = 6)
{
    $chars = str_repeat('0123456789', 10);
    $chars = str_shuffle($chars);
    $str = substr($chars, 0, $len);
    return $str;
}

/**
 * 检查是否是微信浏览器访问
 */
function IsWechatBrowser(){
    if(strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') === false) {
        return false;
    }else{
        return true;
    }
}


/**
 * 用于请求微信接口获取数据
 * @param $url
 * @param bool $post
 * @return bool|string
 */
function get_by_curl($url,$post = false){
    $ch = curl_init();
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if($post){
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$post);
    }
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

//区域奖
     function quyu($OrderInfo,$GoodInfo,$numb){
         
        //系统参数
        $Config = Config();
        //订单地址 天津 河北区 全境123  
        //用空格分割 然后惊醒判断
        $address = explode(' ',$OrderInfo['address']);
        //获取当前用户id
        // $UserID = Session::get('user_id');
        $UserID = $OrderInfo['user_id'];
        // var_dump($UserID);die;
        // $where['user_id'] = $UserID;
        // $where['recommend_id'] = [['neq', 1],['neq', $UserID]];
        //管理奖  将所有上级id取出   自己和admin除外
        // $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
        // $ids = [2];
        //用来判断级差不能比上级低
        $lock = 1;
        //累计级差奖励
        $cha = 0;
        $ids = Db::name('user')->where(['level_1'=>['gt',0],'id'=>['neq',$UserID]])->select();
        
        if($ids){
            //先算区县代
            foreach ($ids as $value){
                $infoaddress = $value['quyu'];
                //有地址再进行判断  并且等级>=$lock
                if($infoaddress && $value['level_1'] >= $lock){
                    //县代
                    if($value['level_1'] == 1){
                        //分割改地址
                        // $infoaddre = explode(' ',$infoaddress);
                        $infoaddre = $infoaddress;
                        //判断两个地址的最后一个是否相同 县有详细地址  只能看截取$address  $infoaddre
                        // $pd = strstr($address[2], $infoaddre[2]);
                        $pd = strstr($address[2], $infoaddre);
                        //如果有  说明是的
                        if($pd){
                            @$money = $GoodInfo['xian']*$numb;//级差奖
                            @$cha = $GoodInfo['xian']*$numb;//级差奖
                            // $tj_money = $money*$Config['yu'];//余额
                            // $tj_money1 = $money*$Config['ji'];//积分
                            $tj_money1 = $money;//积分
                            // $new['balance_4']=$value['balance_4']+$tj_money;  //推荐奖励余额
                            $new['balance_4']=$value['balance_4']+$tj_money1;  //推荐奖励积分
                            $new['person_achievement']=$value['person_achievement']+$money;  //个人收益
                            // FinanceAdd($value['id'], $UserID, $tj_money, 4, 11, '代理奖余额');
                            if($tj_money1 > 0){
                                FinanceAdd($value['id'], $UserID, $tj_money1, 4, 11, '区县代奖励',$OrderInfo['order_id']);
                            }
                            
                            Db::name('user')->where(['id'=>$value['id']])->update($new);
                            $lock = $value['level'] + 1;
                        }
                    }
                }
                
            }
            //市代
            foreach ($ids as $value){
                $infoaddress = $value['quyu'];
                //有地址再进行判断  并且等级>=$lock
                if($infoaddress && $value['level_1'] >= $lock){
                    //市代
                    if($value['level_1'] == 2){
                        //分割改地址
                        // $infoaddre = explode(' ',$infoaddress);
                        $infoaddre = $infoaddress;
                        //判断两个地址的中间一个是否相同 
                        // if($address[1] == $infoaddre[1]){
                        if($address[1] == $infoaddre){
                            @$money = $GoodInfo['shi']*$numb - $cha;//级差奖
                            @$cha = $GoodInfo['shi']*$numb;//级差奖
                            // $tj_money = $money*$Config['yu'];//余额
                            // $tj_money1 = $money*$Config['ji'];//积分
                            $tj_money1 = $money;//积分
                            // $new['balance_4']=$value['balance_4']+$tj_money;  //推荐奖励余额
                            $new['balance_4']=$value['balance_4']+$tj_money1;  //推荐奖励积分
                            $new['person_achievement']=$value['person_achievement']+$money;  //个人收益
                            // FinanceAdd($value['id'], $UserID, $tj_money, 4, 11, '代理奖余额');
                            if($tj_money1 > 0){
                                FinanceAdd($value['id'], $UserID, $tj_money1, 4, 11, '市代奖励',$OrderInfo['order_id']);
                            }
                            
                            Db::name('user')->where(['id'=>$value['id']])->update($new);
                            $lock = $value['level'] + 1;
                        }
                    }
                    
                }
                
            }
            //省代
            foreach ($ids as $value){
                $infoaddress = $value['quyu'];
                //有地址再进行判断  并且等级>=$lock
                if($infoaddress && $value['level_1'] >= $lock){
                    
                    //省代
                    if($value['level_1'] == 3){
                        //分割改地址
                        // $infoaddre = explode(' ',$infoaddress);
                        $infoaddre = $infoaddress;
                        //判断两个地址的中间一个是否相同 
                        // if($address[0] == $infoaddre[0]){
                        if($address[0] == $infoaddre){
                            @$money = $GoodInfo['sheng']*$numb - $cha;//级差奖
                            @$cha = $GoodInfo['sheng']*$numb;//级差奖
                            // $tj_money = $money*$Config['yu'];//余额
                            // $tj_money1 = $money*$Config['ji'];//积分
                            $tj_money1 = $money;//积分
                            // $new['balance_4']=$value['balance_4']+$tj_money;  //推荐奖励余额
                            $new['balance_4']=$value['balance_4']+$tj_money1;  //推荐奖励积分
                            $new['person_achievement']=$value['person_achievement']+$money;  //个人收益
                            // FinanceAdd($value['id'], $UserID, $tj_money, 4, 11, '代理奖余额');
                            if($tj_money1 > 0){
                                FinanceAdd($value['id'], $UserID, $tj_money1, 4, 11, '省代奖励',$OrderInfo['order_id']);
                            }
                            
                            Db::name('user')->where(['id'=>$value['id']])->update($new);
                            $lock = $value['level'] + 1;
                        }
                    }
                }
                
            }
        }
        
    }
    
    //参团人
     function tuan($OrderInfo){
        
        $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
        //获取当前用户id
        // $UserID = Session::get('user_id');
        $UserID = $OrderInfo['user_id'];
        //参团人数+1  参团人拼接进去
        $ptdata['can_people'] = $pt['can_people'] + 1;
        if($pt['can']){
            $ptdata['can'] = $pt['can'] .','.$UserID;
        }else{
            $ptdata['can'] = $UserID;
        }
        
        if($ptdata['can_people'] >= $pt['pt_people']){
            $ptdata['status'] = 2;
        }
        Db::name('user_pt')->where(['id'=>$pt['id']])->update($ptdata);
    }
    
    //开奖
     function kai($OrderInfo,$GoodInfo){
    // public function kai(){
        $pt = Db::name('user_pt')->where(['pt_id'=>$OrderInfo['pt_id']])->find();
        // $pt = Db::name('user_pt')->where(['pt_id'=>20210401145713706])->find();
        //2准备开奖   
        if($pt['status'] == 2){
            //参加的人
            $peoples = explode(',',$pt['can']);
            //将团长移除  不开奖
            $key=array_search($pt['chuang'] ,$peoples);
            array_splice($peoples,$key,1);
            //中奖的人  随机取   array_rand是取键   所以array_flip  键值交换下
            $zhong = array_rand(array_flip($peoples),$pt['get_people']);
            //循环处理所有拼团的人
            foreach ($peoples as $v){
                //获取参团人信息
                $info = Db::name('user')->where(['id'=>$v])->find();
                //获取参团人订单信息
                $order = Db::name('user_order')->where(['pt_id'=>$pt['pt_id'],'user_id'=>$v])->find();
                //商品信息
                $GoodInfo = Db::name('goods')->where(['id'=>$order['goods_id'] ])->find();
                //处理中奖
                if(in_array($v,$zhong)){
                    //获取购买金额
                    if($v == $pt['chuang']){
                        $money = $pt['quan']*$order['num'];
                    }else{
                        $money = $pt['price']*$order['num'];
                    }
                    
                    if($info){
                        //将释放积分存入user表
                        $sf['sfjifen'] = $info['sfjifen'] + $money;
                        Db::name('user')->where(['id'=>$v])->update($sf);
                        
                        //修改订单状态为5   成功
                        $success['status'] = 5;
                        Db::name('user_order')->where(['id'=>$order['id']])->update($success);
                        //团队业绩
                        Db::query('call add_recommend_num(:id,:num )',['id'=>$v,'num'=>$money]);    // team_num
                        //直推奖
                        $higherInfo= Db::name('user')->where(['id'=>$info['recommend']])->find();
                        if($higherInfo){
                            $tj_money = $GoodInfo['reward_1']*$order['num'];//推荐奖
                            $tj_money1 = $GoodInfo['zhiyu']*$order['num'];//推荐奖
                            //店铺级以上  直推奖励到余额    其他积分
                            if($higherInfo['level'] >= 3){
                                $recommend['balance_4']=$higherInfo['balance_4']+$tj_money1;  //推荐奖励余额
                                $recommend['balance_1']=$higherInfo['balance_1'];
                                // $recommend['person_achievement']=$higherInfo['person_achievement']+$tj_money;  //个人收益
                                $ms = '推荐奖余额';
                                if($tj_money1 > 0){
                                    FinanceAdd($info['recommend'], $info['id'], $tj_money1, 4, 11, $ms,$OrderInfo['order_id']);
                                }
                                
                            }else{
                                $recommend['balance_1']=$higherInfo['balance_1']+$tj_money;  //推荐奖励积分
                                $recommend['balance_4']=$higherInfo['balance_4'];
                                // $recommend['person_achievement']=$higherInfo['person_achievement']+$tj_money;  //个人收益
                                $ms = '推荐奖积分';
                                if($tj_money > 0){
                                    FinanceAdd($info['recommend'], $info['id'], $tj_money, 1, 11, $ms,$OrderInfo['order_id']);
                                }
                                
                            }
                            $recommend['person_achievement']=$higherInfo['person_achievement']+$tj_money;  //个人收益
                            Db::name('user')->where(['id'=>$info['recommend']])->update($recommend);
                            // FinanceAdd($info['recommend'], $info['id'], $tj_money, 4, 11, $ms);
                        }
                        
                        // //区域奖
                        quyu($order,$GoodInfo);
                    }
                }else{
                    //未中奖
                    //获取购买金额
                    if($v == $pt['chuang']){
                        $money = $pt['quan']*$order['num'];
                    }else{
                        $money = $pt['price']*$order['num'];
                    }
                    if($info){
                        //修改订单状态为6  失败
                        $false['status'] = 11;
                        Db::name('user_order')->where(['id'=>$order['id']])->update($false);
                        //余额  =  原余额 + 退还 +  红包
                        // if($OrderInfo['pay_type'] == 9){
                        //     wxrefund($out_trade_no,$OrderInfo['amount']*100,$OrderInfo['amount']*100);
                        //     FinanceAdd($info['id'], $info['id'], $OrderInfo['amount'], 9, 11, '拼团退款');
                        // }else{
                        //     $back['balance_4'] = $info['balance_4'] + $money + $pt['hongbao'];
                        //     FinanceAdd($info['id'], $info['id'], $money, 4, 11, '拼团退款');
                        //     Db::name('user')->where(['id'=>$info['id']])->update($back);
                        // }
                        
                        
                        
                    }
                }
            }
            //存入中奖人  修改状态3
                $zj['zhong'] = implode(',',$zhong);
                $zj['status'] = 3;
                Db::name('user_pt')->where(['id'=>$pt['id']])->update($zj);
        }
        // var_dump($order);die;
    }
    
    //店铺额外奖励
     function dian($GoodInfo,$OrderInfo){
        //用户信息
        // $UserInfo = UserInfo(['id'=>Session::get('user_id')]);
        $UserInfo = UserInfo(['id'=>$OrderInfo['user_id']]);
        // var_dump($UserInfo);die;
        $higherInfo= Db::name('user')->where(['id'=>$UserInfo['recommend']])->find();
        if($higherInfo['level'] == 3 ){
            if($GoodInfo['dian'] != null){
                $dian['balance_4']=$higherInfo['balance_4'] + $GoodInfo['dian'];  //店铺奖励余额
                if($GoodInfo['dian'] > 0){
                    FinanceAdd($higherInfo['id'], $UserInfo['id'], $GoodInfo['dian'], 4, 11, '店铺奖励');
                }
                
                Db::name('user')->where(['id'=>$higherInfo['id']])->update($dian);
            }
        }else{
            //获取当前用户id
            // $UserID = Session::get('user_id');
            $UserID = $OrderInfo['user_id'];
            $where['user_id'] = $UserID;
            $where['recommend_id'] = [['neq', 1],['neq', $UserID]];
            //升级时  将所有上级id取出   自己和admin除外
            $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
            //遍历处理
            foreach ($ids as $v){
                //获取信息
                $info = UserInfo(['id'=>$v]);
                if($info['level'] == 3){
                    if($GoodInfo['dian'] != null){
                        $dian['balance_4']=$info['balance_4'] + $GoodInfo['dian'];  //店铺奖励余额
                        if($GoodInfo['dian'] > 0){
                            FinanceAdd($info['id'], $UserInfo['id'], $GoodInfo['dian'], 4, 11, '店铺奖励');
                        }
                        
                        Db::name('user')->where(['id'=>$info['id']])->update($dian);
                        break;
                    }
                    
                }
            }
        }
    }
    
     function wxrefund($out_trade_no,$total_fee,$refund_fee){
        require_once __DIR__."/../vendor/WxPayv3/lib/WxPay.Api.php";
        require_once __DIR__."/../vendor/WxPayv3/lib/WxPay.Config.php";
        require_once __DIR__."/../vendor/WxPayv3/lib/WxPay.Data.php";
        $out_trade_no = $out_trade_no;
        $total_fee = $total_fee;
        $refund_fee =$refund_fee;
        $input = new \WxPayRefund();
        $input->SetOut_trade_no($out_trade_no);
        $input->SetTotal_fee($total_fee);
        $input->SetRefund_fee($refund_fee);
        $input->SetOut_refund_no(\WxPayConfig::MCHID.date("YmdHis"));
        $input->SetOp_user_id(\WxPayConfig::MCHID);
        \WxPayApi::refund($input);
         dump(\WxPayApi::refund($input));
         exit();
    }
    
    
    /**
 * 登录记录
 */
function LoginList($Where=[]){
    $query = request()->param();
    if (empty($query)){
        $query = [
        ];
    }
    if(empty($Where)){
        $List = \think\Db::name('user_login')->order('time desc')->paginate('13',false,['query'=>$query]);
    }else{
        $List = \think\Db::name('user_login')->where($Where)->order('time desc')->paginate('1',false,['query'=>$query]);

    }

    $UserList = $List->toArray()['data'];
    $Page = $List->render();

    // foreach( $UserList as $k=>$v){
    //     //等级信息
    //     $LevelInfo = \think\Db::name('user_level')->where(['id'=>$UserList[$k]['level']])->find();
    //     if(empty($LevelInfo)){
    //         $UserList[$k]['level'] = "普通用户";
    //     }else{
    //         $UserList[$k]['level'] = $LevelInfo['name'];
    //     }

    //     //推荐人信息
    //     $RecommendInfo = UserInfo(['id'=>$UserList[$k]['recommend']]);
    //     $UserList[$k]['recommend'] = $RecommendInfo['username'];
    // }

    return ['UserList'=>$UserList,'Page'=>$Page];
}

/**
 * 登录记录条数
 */
function LoginCount($Where=[]){
    if(empty($Where)){
        $UserCount = \think\Db::name('user_login')->count();
    }else{
        $UserCount = \think\Db::name('user_login')->where($Where)->count();
    }

    return $UserCount;
}

/**
 * 2021/6/23 19:05
 * 升级
 */
function uplevel($OrderInfo){
    //获取升级条件配置
    $levelup = Db::name('user_level')->select();
//     var_dump($levelup[3]);die;
    //获取当前用户id
    $UserID = $OrderInfo['user_id'];
    $where['user_id'] = $UserID;
    $where['recommend_id'] = [['neq', 1],['neq', $UserID]];
    //升级时  将所有上级id取出   自己和admin除外
    $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
    //遍历处理
    foreach ($ids as $v){
        //获取信息
        $info = UserInfo(['id'=>$v]);
        //代理->加盟店
        if($info['level'] == 3){
            $pd1 = Db::name('user')->where(['recommend'=>$info['id'],'level'=>['egt',3]])->count();
            if($pd1 >= $levelup[3]['number']){
                $upda['level'] = 4;
                Db::name('user')->where(['id'=>$info['id']])->update($upda);
            }
        }
        //加盟店->区县
        if($info['level'] == 4){
            $pd2 = Db::name('user')->where(['recommend'=>$info['id'],'level'=>['egt',4]])->count();
            if($pd2 >= $levelup[4]['number']){
                $upda['level'] = 5;
                Db::name('user')->where(['id'=>$info['id']])->update($upda);
            }
        }
        //区县->市级
        if($info['level'] == 5){
            $pd3 = Db::name('user')->where(['recommend'=>$info['id'],'level'=>['egt',5]])->count();
            if($pd3 >= $levelup[5]['number']){
                $upda['level'] = 6;
                Db::name('user')->where(['id'=>$info['id']])->update($upda);
            }
        }
        //市级->省级
        if($info['level'] == 6){
            $pd4 = Db::name('user')->where(['recommend'=>$info['id'],'level'=>['egt',6]])->count();
            if($pd4 >= $levelup[6]['number']){
                $upda['level'] = 7;
                Db::name('user')->where(['id'=>$info['id']])->update($upda);
            }
        }
        //省级->合伙人
        if($info['level'] == 7){
            $pd5 = Db::name('user')->where(['recommend'=>$info['id'],'level'=>['egt',7]])->count();
            if($pd5 >= $levelup[7]['number']){
                $upda['level'] = 8;
                Db::name('user')->where(['id'=>$info['id']])->update($upda);
            }
        }

    }
}

//级差奖
//function jicha($goods,$OrderInfo){
//    //系统参数
//    $Config = Config();
//    // var_dump($Config['yu']);//余额
//    // var_dump($Config['ji']);//积分
//    //获取当前用户id
//    $UserID = $OrderInfo['user_id'];
//    $where['user_id'] = $UserID;
//    $where['recommend_id'] = [['neq', 1],['neq', $UserID]];
//    //管理奖  将所有上级id取出   自己和admin除外
//    $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
//    // $ids = [149,151,152,153,154];
//    //用来判断平级奖等级不能比上级低
//    $lock = 2;
//    $lock1 = 2;
//    //用来判断平级奖拿的次数  拿过的等级全放进去  3 4 5 6-12
//    $ci = array();
//    //累计级差奖励
//    $cha = 0;
//    //累计平级奖励
//    $ping = 0;
//    // var_dump($ids);die;
//    foreach ($ids as $val){
//        //获取信息
//        $info = UserInfo(['id'=>$val]);
//        //3 4 5 6-12 将6-12等级全设置成6   用来区分1-4星店主
//        if($info['level'] >8){
//            $le = 8;
//        }else{
//            $le = $info['level'];
//        }
//        //先判断在不在数组中  在数次数
//        if(in_array($le,$ci)){
//            $count = array_count_values($ci)[$le];
//        }else{
//            $count = 0;
//        }
//        //会员等级>=3 即起码一星店主      会员等级>=上级等级     出现次数=0
//        //第一次出现  级差奖
//        if($le >= 2 && $le >= $lock && $count == 0){
//            //一星店主
//            if($le == 2){
//                $money = $goods['oneji'];//级差奖
//                $cha = $goods['oneji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, 'VIP级差奖');
//                }
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 3){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['twoji'] - $cha - $ping;//级差奖
//                $money = $goods['twoji'] - $cha;//级差奖
//                $cha = $goods['twoji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '代理级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 4){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['threeji'] - $cha - $ping;//级差奖
//                $money = $goods['threeji'] - $cha;//级差奖
//                $cha = $goods['threeji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '加盟店级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 5){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['fourji'] - $cha - $ping;//级差奖
//                $money = $goods['fourji'] - $cha;//级差奖
//                $cha = $goods['fourji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '区县加盟商级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 6){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['fourji'] - $cha - $ping;//级差奖
//                $money = $goods['fiveji'] - $cha;//级差奖
//                $cha = $goods['fiveji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '市级加盟商级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 7){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['fourji'] - $cha - $ping;//级差奖
//                $money = $goods['sixji'] - $cha;//级差奖
//                $cha = $goods['sixji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '省级加盟商级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 8){
//                if(in_array($le-1,$ci)){
//                    if(array_count_values($ci)[$le-1] >= 2){
//                        $ping = $ping;
//                    }else{
//                        $ping = 0;
//                    }
//                }else{
//                    $ping = 0;
//                }
//                // $money = $GoodInfo['fourji'] - $cha - $ping;//级差奖
//                $money = $goods['sevenji'] - $cha;//级差奖
//                $cha = $goods['sevenji'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '合伙人级差奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            //将等级设置为当前等级
//            $lock = $le;
//            //将当前等级放入数组中,用来判断该等级出现次数
//            array_push($ci,$le);
//        }
//        //会员等级>=3 即起码一星店主      会员等级>=上级等级     出现次数=1
//        //第二次出现  平级奖
//        if($le >= 2 && $le >= $lock1 && $count == 1){
//            //一星店主
//            if($le == 2){
//                $money = $goods['onep'];//平级奖
//                $ping = $goods['onep'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, 'VIP平级奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 3){
//                $money = $goods['twop'] - $ping;//平级奖
//                $ping = $goods['twop'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '代理平级奖');
//                }
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 4){
//                $money = $goods['threep'] - $ping;//平级奖
//                $ping = $goods['threep'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '加盟店平级奖');
//                }
//
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 5){
//                $money = $goods['fourp'] - $ping;//平级奖
//                $ping = $goods['fourp'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '区县加盟店平级奖');
//                }
//
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 6){
//                $money = $goods['fivep'] - $ping;//平级奖
//                $ping = $goods['fivep'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '市级加盟店平级奖');
//                }
//
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 7){
//                $money = $goods['sixp'] - $ping;//平级奖
//                $ping = $goods['sixp'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '省级加盟店平级奖');
//                }
//
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            if($le == 8){
//                $money = $goods['sevenp'] - $ping;//平级奖
//                $ping = $goods['sevenp'];
//                $tj_money = $money;//推荐奖余额
//                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
//                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
//                if($tj_money > 0){
//                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '合伙人平级奖余额');
//                }
//
//
//                Db::name('user')->where(['id'=>$info['id']])->update($new);
//            }
//            //将等级设置为当前等级
//            $lock1 = $le;
//            //将当前等级放入数组中,用来判断该等级出现次数
//            array_push($ci,$le);
//        }
//    }
//}
function jicha($goods,$OrderInfo,$numb,$level){
    //系统参数
    $Config = Config();
    // var_dump($Config['yu']);//余额
    // var_dump($Config['ji']);//积分
    //获取当前用户id
    $UserID = $OrderInfo['user_id'];
    $userinfo = UserInfo(['id'=>$UserID]);
    $where['user_id'] = $UserID;
    $where['recommend_id'] = [['neq', 1],['neq', $UserID]];
    //管理奖  将所有上级id取出   自己和admin除外
    $ids= Db::name('user_recommend')->where($where)->column('recommend_id');
    // $ids = [149,151,152,153,154];
//    var_dump($ids);die;
    //用来判断平级奖等级不能比上级低
    $lock = $level;
    $lock1 = $level;
    //用来判断平级奖拿的次数  拿过的等级全放进去  3 4 5 6-12
    $ci = array();
    //累计级差奖励
    if($level == 1){
        $cha = 0;
    }elseif($level == 2){
        $cha = $goods['oneji'];
    }elseif($level == 3){
        $cha = $goods['twoji'];
    }elseif($level == 4){
        $cha = $goods['threeji'];
    }elseif($level == 5){
        $cha = $goods['fourji'];
    }elseif($level == 6){
        $cha = $goods['fiveji'];
    }elseif($level == 7){
        $cha = $goods['sixji'];
    }elseif($level == 8){
        $cha = $goods['sevenji'];
    }
//    var_dump($cha);
//    $cha = 0;
    //累计平级奖励
    $ping = 0;
    // var_dump($ids);die;
    foreach ($ids as $val){
        if($level == 2){
            array_push($ci,2);
        }elseif($level == 3){
            array_push($ci,3);
        }elseif($level == 4){
            array_push($ci,4);
        }elseif($level == 5){
            array_push($ci,5);
        }elseif($level == 6){
            array_push($ci,6);
        }elseif($level == 7){
            array_push($ci,7);
        }elseif($level == 8){
            array_push($ci,8);
        }else{
            $ci = $ci;
        }
//        var_dump($ci);die;
        //获取信息
        $info = UserInfo(['id'=>$val]);
        //3 4 5 6-12 将6-12等级全设置成6   用来区分1-4星店主
        if($info['level'] >8){
            $le = 8;
        }else{
            $le = $info['level'];
        }
        //先判断在不在数组中  在数次数
        if(in_array($le,$ci)){
            $count = array_count_values($ci)[$le];
        }else{
            $count = 0;
        }
        //会员等级>=3 即起码一星店主      会员等级>=上级等级     出现次数=0
        //第一次出现  级差奖
        if($le >= 2 && $le >= $lock && $count < 2){
            //VIP级差
            if($le == 2 && $count == 0){
                $money = $goods['oneji']*$numb;//级差奖
                $cha = $goods['oneji']*$numb;

                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, 'VIP级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //VIP平级
            if($le == 2 && $count == 1){
                $money = $goods['onep']*$numb;//平级奖
                $cha = $cha + $goods['onep']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, 'VIP平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //代理级差
            if($le == 3 && $count == 0){
                $money = $goods['twoji']*$numb - $cha;//级差奖
                $cha = $goods['twoji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '代理级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //代理平级
            if($le == 3 && $count == 1){
                $money = $goods['twop']*$numb;//平级奖
                $cha = $cha + $goods['twop']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '代理平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //加盟店级差
            if($le == 4 && $count == 0){
                $money = $goods['threeji']*$numb - $cha;//级差奖
                $cha = $goods['threeji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '加盟店级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //加盟店平级
            if($le == 4 && $count == 1){
                $money = $goods['threep']*$numb;//平级奖
                $cha = $cha + $goods['threep']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '加盟店平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //区县加盟店级差
            if($le == 5 && $count == 0){
                $money = $goods['fourji']*$numb - $cha;//级差奖
                $cha = $goods['fourji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '区县加盟商级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //区县加盟商平级
            if($le == 5 && $count == 1){
                $money = $goods['fourp']*$numb;//平级奖
                $cha = $cha + $goods['fourp']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '区县加盟店平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //市级加盟商级差
            if($le == 6 && $count == 0){
                $money = $goods['fiveji']*$numb - $cha;//级差奖
                $cha = $goods['fiveji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '市级加盟商级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //市级加盟商平级
            if($le == 6 && $count == 1){
                $money = $goods['fivep']*$numb;//平级奖
                $cha = $cha + $goods['fivep']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '市级加盟店平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //升级加盟商级差
            if($le == 7 && $count == 0){
                $money = $goods['sixji']*$numb - $cha;//级差奖
                $cha = $goods['sixji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '省级加盟商级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //省级加盟商平级
            if($le == 7 && $count == 1){
                $money = $goods['sixp']*$numb;//平级奖
                $cha = $cha + $goods['sixp']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '省级加盟店平级奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //合伙人级差
            if($le == 8 && $count == 0){
                $money = $goods['sevenji']*$numb - $cha;//级差奖
                $cha = $goods['sevenji']*$numb;
                $tj_money = $money;//推荐奖余额
                $new['balance_4']=$info['balance_4']+$tj_money;  //推荐奖励余额
                $new['person_achievement']=$info['person_achievement']+$money;  //个人收益
                if($tj_money > 0){
                    FinanceAdd($info['id'], $UserID, $tj_money, 4, 11, '合伙人级差奖',$OrderInfo['order_id']);
                    Db::name('user')->where(['id'=>$info['id']])->update($new);
                }
            }
            //将等级设置为当前等级
            $lock = $le;
            //将当前等级放入数组中,用来判断该等级出现次数
            array_push($ci,$le);
        }

    }
}

function filterEmoji($str)
{
    $str = preg_replace_callback( '/./u',
        function (array $match) {
            return strlen($match[0]) >= 4 ? '' : $match[0];
        },
        $str);
    return $str;
}